package com.example.optimizaapp.domain.Utilities;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.optimizaapp.LoginActivity;
import com.example.optimizaapp.domain.ManejadorUsuario;
import com.example.optimizaapp.domain.Usuario;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

public class LoginUserService extends AsyncTask<String, Void, String>{
	private ArrayList <Usuario> users;
	private ProgressDialog progressDialog;
	private LoginActivity activity;
	
	private static final String USUARIO_KEY = "usuario";
	private static final String EMAIL_KEY = "email";
	private static final String NOMBRE_USUARIO = "usuario";
	private static final String PASSWORD_USUARIO = "password";
	private static final String ID_KEY = "id";
	
	public LoginActivity getActivity() {
		return activity;
	}

	public void setActivity(LoginActivity activity) {
		this.activity = activity;
	}
	
	public ArrayList<Usuario> getUsers() {
		return users;
	}

	public void setUsers(ArrayList<Usuario> users) {
		this.users = users;
	}
	
	public LoginUserService (LoginActivity loginActivity, ProgressDialog pd){
		this.setActivity(loginActivity);
		this.progressDialog = pd;

	}
	
	@Override
	protected void onPreExecute()
	{
		progressDialog.show();
	}
	
	
	@Override
	protected String doInBackground(String... params) {
		
		String returned = Webservices.callWebService(params[0]);
		
		try {
			this.users = new ArrayList<Usuario>();
			JSONObject response = new JSONObject(returned);
			Log.d("RESPONSE", returned);
			JSONArray users = response.getJSONArray(USUARIO_KEY);
			
			 for(int i = 0; i < users.length(); i++){
				 JSONObject jUser = users.getJSONObject(i);
				 Usuario u = new Usuario();
				 u.id = jUser.getInt(ID_KEY);
				 u.email = jUser.getString(EMAIL_KEY);
				 u.nombreUsuario = jUser.getString(NOMBRE_USUARIO);
				 u.password = jUser.getString(PASSWORD_USUARIO);
				 this.getUsers().add(u);
			 }
			 if (this.getUsers().size()>0){
				 ManejadorUsuario.getManejadorUsuario().setUsuarioLogueado(this.getUsers().get(0));
								
			 }
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RuntimeException e){
			e.printStackTrace();

		}
		
		return returned;
	}
	
	
	protected void onPostExecute(String result) {
		progressDialog.dismiss();
		activity.verifyLoggedUser();
    }

	
	
	
}
